package com.coder.widget.guide

import android.app.Activity
import android.graphics.Path
import android.graphics.Rect
import android.graphics.RectF
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout

/**
 * @description 用户引导视图，需配合HoleDrawable一起使用
 * @author yuhus
 * @date 2021/4/11 21:39
 */
fun ViewGroup.setGuideView(replaceView: View, targetView: View, maskColor: Int): ViewGroup {
    targetView.post {
        val targetRect = Rect()
        targetView.getGlobalVisibleRect(targetRect)

        // replaceView设置为占位隐藏
        replaceView.visibility = View.INVISIBLE
        // 设置背景
        val outPath = Path().also {
            it.addRect(RectF(targetRect), Path.Direction.CW)
        }
        background = HoleDrawable(maskColor, outPath)

        // 改变replaceView宽高
        val params = replaceView.layoutParams
        params?.let {
            it.width = targetRect.width()
            it.height = targetRect.height()
            replaceView.layoutParams = it
        }
        // 内容滚动到合适位置
        replaceView.post {
            val replaceRect = Rect()
            replaceView.getGlobalVisibleRect(replaceRect)
            scrollTo(replaceRect.left - targetRect.left, replaceRect.top - targetRect.top)
        }
    }
    return this
}

fun ViewGroup.addToDecorView(activity: Activity) {
    (activity.window.decorView as FrameLayout).addView(this)
}

fun ViewGroup.removeFromDecorView(activity: Activity) {
    (activity.window.decorView as FrameLayout).removeView(this)
}